package com.rover.system.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import com.rover.system.dao.BaseDao;
import com.rover.system.entity.Resource;

@Service("resourceService")
@Transactional
public class ResourceService{
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private BaseDao dao;
	
	
	
	@Transactional
	public void initData(String fileName) throws ServiceException {
        dao.executeSQL("delete from s_Resource",null);

		logger.debug("开始装载资源初始数据");
		File resourcetxt = new File(fileName);

		String star[] = {};
	  	try {
			// use google guava
			List<String> lines = Files.readLines(resourcetxt, Charsets.UTF_8);
			Resource resource;
			int line = 1;
			for (String thisLine : lines) {
				//第一行是标题
				if (line == 1) {
					line++;
					continue;
				}
			
				star =thisLine.split(",");
				if (star[0].trim().equals("")){
					continue;
				}
				resource = new Resource();
                resource.setId(Integer.valueOf( star[0].trim()));
                resource.setText( star[1].trim());
                resource.setUrl(star[2].trim());
                resource.setLeaf(Integer.valueOf(star[3].trim()));
                resource.setParentId (Integer.valueOf(star[4].trim()));
              
                resource.setOrderNo(Integer.valueOf(star[5].trim()));
                resource.setState(star[6].trim());
                resource.setIconCls(star[7].trim());
                resource.setPermission(star[8].trim());
                if (star.length > 9) {
                    resource.setType(star[9].trim());
                } else {
                    resource.setType("1");
                }
                dao.<Resource>saveOrUpdate(resource);
			}
		} catch (Exception e) {
			logger.error("str[]:" + StringUtils.join(star, ","));
			logger.error("装载资源数据出错:" + e, e);
			throw new ServiceException("导入资源时，服务器发生异常");
		} finally {
			//br.close();
		}
	}
	
    @Transactional(readOnly = true)
    public List<Resource> getResource(Integer parentId,List<String> permissions) throws ServiceException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("parentId", parentId);
        params.put("permissions", permissions);
        return dao.findHql("from Resource r where r.parentId=:parentId and r.permission in(:permissions) " +
                "order by r.id",params);

    }

	/*
	 * 根据父id返回子资源
	 * @parentId  父id
	 * */
	@Transactional(readOnly = true)
	public List<Resource> selectResource(Integer parentId) throws ServiceException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("parentId", parentId);
		return dao.findHql("from Resource t where t.parentId=:parentId  order by t.id",params);

	}
	/*
	 * 根据父id返回子资源
	 * @parentId  父id
	 * @isAdmin  是否是管理员
	 * @role_ID  用户id（只有不是管理员的时候才用到）
	 * */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Resource> selectResource(Integer parentId,Boolean isAdmin,List<String> liRole) throws ServiceException {
		if(isAdmin){
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("parentId", parentId);
		    return dao.findHql("from Resource t where t.parentId=:parentId order by t.id",params);
		}
		else{
			//单个角色
		   // Query q=resourceDao.getCurrentSession().createQuery("select r from  RoleResource rr,Resource r where rr.resource_ID=r.id and rr.role_ID=:role_ID and r.parentId=:parentId");
			//q.setInteger("role_ID", role_ID);
			//多个角色
			String hql="from Resource r where r.id in(select distinct rr.resource_ID from RoleResource rr where rr.role_ID in(:alist)) and r.parentId=:parentId order by r.id";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("alist", liRole);
			params.put("parentId", parentId);
//			Query q=resourceDao.getCurrentSession().createQuery("from Resource r where r.id in(select distinct rr.resource_ID from RoleResource rr where rr.role_ID in(:alist)) and r.parentId=:parentId order by r.id");
//			q.setParameterList("alist", liRole);
//		    q.setInteger("parentId", parentId);
		   return dao.findHql(hql, params);
		}
	}
	
	/*
	 * 根据父列id表返回子资源
	 * @liParentId 父id列表
	 * */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Resource> selectResource(List<Integer> liParentId) throws ServiceException {
//			Query q=resourceDao.getCurrentSession().createQuery("from Resource r where r.id in(:alist) order by r.id");
//			q.setParameterList("alist", liParentId);
//		   return q.list();
        if(liParentId.size()==0)
            return new ArrayList<Resource> ();
        else{
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("alist", liParentId);
		return dao.findHql("from Resource r where r.id in(:alist) order by r.id",params);
        }
	}
	
	
	
	@Transactional(readOnly = true)
	public List<Resource> getRoleResource(Integer parentId) throws ServiceException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("parentId", parentId);
		return dao.findHql("from Resource t where t.parentId=:parentId order by t.id",params);

	}
	
	@Transactional(readOnly = true)
	public List<Resource> getAllResources(){
		return dao.findHql("from Resource",null);
	}
}
